const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const { regardList, targetTime, ticketCount, userTickets } = event
  const { OPENID } = cloud.getWXContext()

  try {
    // 如果已有记录，则更新，否则插入
    const record = await db.collection('lotteryData').where({ _openid: OPENID }).get()
    if (record.data.length > 0) {
      await db.collection('lotteryData').where({ _openid: OPENID }).update({
        data: {
          _openid: OPENID,
          regardList,
          targetTime,
          ticketCount,
          userTickets,
          updateTime: new Date()
        }
      })
    } else {
      await db.collection('lotteryData').add({
        data: {
          _openid: OPENID,
          regardList,
          targetTime,
          ticketCount,
          userTickets,
          updateTime: new Date()
        }
      })
      console.log("fdsa");
    }

    return {
      code: 0,
      msg: '数据更新成功'
    }
  } catch (e) {
    return {
      code: 1,
      msg: '更新失败',
      error: e
    }
  }
}
